library handlers;
import 'dart:html';
import 'dart:convert';
import 'package:mundus/src/new/internal.dart';
part 'constants.dart';

class Handlers {
   Actions _act;
   DivElement _cont;
   TextAreaElement _clip;

   Handlers (DivElement cont) {
      String vert = cont.style.height;
      String horz = cont.style.width;
      if (!vert.endsWith('em')) throw new ArgumentError('$cont');
      if (!horz.endsWith('em')) throw new ArgumentError('$cont');
      int height = int.parse(vert.substring(0, vert.length - 2));
      int width = int.parse(horz.substring(0, vert.length - 2)) * 2;

      // initialize instance variables
      _act = new Actions(height, width);
      _cont = cont;
      _clip = new TextAreaElement();

      // insert into DOM
      _cont.children.add(_act.pe);
      _cont.children.add(_clip);

      // styling
      _cont.style.position = 'relative';
      _clip.style
         ..position = 'absolute'
         ..opacity = '0'
         ..zIndex = '-1'
         ..top = '0'
         ..left = '0'
         ..height = '7px'
         ..width = '7px';

      // install handlers
      _cont.attributes['tabIndex'] = '0';
      _cont.onKeyDown.listen(_keyDown);
      _cont.onKeyPress.listen(_keyPress);
      _clip.onCut.listen(_cut);
      _clip.onCopy.listen(_copy);
      _clip.onPaste.listen(_paste);
      _cont.focus();
   }

   void _keyDown (KeyboardEvent ke) {
      int key = ke.keyCode;
      if (badKeys.contains(key)) ke.preventDefault();
      if (ke.shiftKey) {
         switch (key) {
            case LEFT : _act.shiftLeft(); break;
            case RIGHT : _act.shiftRight(); break;
            case UP : _act.shiftUp(); break;
            case DOWN : _act.shiftDown(); break;
         }
      }
      else if (ke.ctrlKey) {
         switch (key) {
            case CUT : _clip.focus(); break;
            case COPY : _clip.focus(); break;
            case PASTE : _clip.focus(); break;
         }
      }
      else {
         switch (key) {
            case LEFT : _act.left(); break;
            case RIGHT : _act.right(); break;
            case UP : _act.up(); break;
            case DOWN : _act.down(); break;

            case ENTER : _act.character('\n'); break;
            case BACKSPACE : _act.backspace(); break;
         }
      }
   }
   void _keyPress (KeyboardEvent ke) {
      String c = ASCII.decode([ke.charCode]);
      _act.character(c);
   }

   void _cut (Event e) {
      e.preventDefault();
      _cont.focus();
      String data = _act.cut();
      if (data == '') return;
      e.clipboardData.setData('text/plain', data);
   }
   void _copy (Event e) {
      e.preventDefault();
      _cont.focus();
      String data = _act.copy();
      if (data == '') return;
      e.clipboardData.setData('text/plain', data);
   }
   void _paste (Event e) {
      e.preventDefault();
      _cont.focus();
      String data = e.clipboardData.getData('text/plain');
      if (data == '') return;
      _act.paste(data);
   }
}
